import { create } from 'zustand';
import { v4 as uuidv4 } from 'uuid';
import { FlowNode, FlowConnection, FunctionDefinition, NodeStatus, FunctionParam } from '../common/types';

interface SmartConnection {
  curvature: number;
  avoidCollisions: boolean;
  lastUpdated: number;
}

interface FlowState {
  // 核心状态
  nodes: FlowNode[];
  connections: FlowConnection[];
  functions: FunctionDefinition[];
  selectedNodeId: string | null;
  lastAddedNodeId: string | null;
  
  // 智能连接状态
  smartConnections: Record<string, SmartConnection>;
  avoidingPaths: Record<string, boolean>;
  
  // 操作方法
  addNode: (node: FlowNode) => void;
  removeNode: (nodeId: string) => void;
  updateNodePosition: (nodeId: string, position: { x: number; y: number }) => void;
  updateNodeParams: (nodeId: string, params: Record<string, any>) => void;
  setNodeStatus: (nodeId: string, status: NodeStatus) => void;
  addConnection: (connection: FlowConnection) => void;
  removeConnection: (connectionId: string) => void;
  setSelectedNode: (nodeId: string | null) => void;
  updateConnectionPath: (connId: string) => void;
  recalculateAllPaths: () => void;
  clearRuntimeData: () => void;
  
  // 新增函数操作方法
  loadFunctions: () => Promise<void>;
  setFunctions: (funcs: FunctionDefinition[]) => void;
}

export const useFlowStore = create<FlowState>((set, get) => ({
  // 初始状态
  nodes: [],
  connections: [],
  functions: [], // 初始为空，通过loadFunctions加载
  selectedNodeId: null,
  lastAddedNodeId: null,
  smartConnections: {},
  avoidingPaths: {},

  // 加载函数模块
  loadFunctions: async () => {
    try {
      // Vite的动态导入方式
      const modules = import.meta.glob('../../functions/*/*.js');
      const loadedFunctions: FunctionDefinition[] = [];

      for (const path in modules) {
        const mod = await modules[path]();
        const folderName = path.split('/')[4]; // 提取文件夹名
        
        loadedFunctions.push({
          id: `${folderName}_${path.split('/').pop()?.replace('.js', '')}`,
          name: mod.meta?.name || path.split('/').pop()?.replace('.js', '') || 'Unnamed Function',
          category: folderName,
          parameters: mod.meta?.parameters || [],
          execute: mod.default
        });
      }

      set({ functions: loadedFunctions });
    } catch (error) {
      console.error('Failed to load functions:', error);
    }
  },

  // 手动设置函数列表
  setFunctions: (funcs) => set({ functions: funcs }),

  // 添加节点
  addNode: (node) => set((state) => {
    const funcDef = state.functions.find(f => f.id === node.functionId);
    if (!funcDef) return state;

    let newConnections = [...state.connections];
    let lastAddedId = node.id;

    // 自动连接到前一个节点
    if (state.lastAddedNodeId && node.id !== state.lastAddedNodeId) {
      newConnections.push({
        id: uuidv4(),
        sourceId: state.lastAddedNodeId, 
        targetId: node.id
      });
      lastAddedId = node.id;
    }

    return {
      nodes: [...state.nodes, node],
      connections: newConnections,
      lastAddedNodeId: lastAddedId
    };
  }),

  // 移除节点
  removeNode: (nodeId) => set((state) => {
    const incoming = state.connections.filter(c => c.targetId === nodeId);
    const outgoing = state.connections.filter(c => c.sourceId === nodeId);
    
    // 过滤掉与该节点相关的连接
    let newConnections = state.connections.filter(
      c => c.sourceId !== nodeId && c.targetId !== nodeId
    );
    
    // 重新连接前后节点
    incoming.forEach(inConn => {
      outgoing.forEach(outConn => {
        if (inConn.sourceId !== outConn.targetId) {
          newConnections.push({
            id: uuidv4(),
            sourceId: inConn.sourceId,
            targetId: outConn.targetId,
          });
        }
      });
    });

    // 清理连接状态
    const removedConnectionIds = [
      ...incoming.map(c => c.id),
      ...outgoing.map(c => c.id)
    ];
    
    const newSmartConnections = { ...state.smartConnections };
    removedConnectionIds.forEach(id => delete newSmartConnections[id]);

    return {
      nodes: state.nodes.filter(n => n.id !== nodeId),
      connections: newConnections,
      lastAddedNodeId: state.lastAddedNodeId === nodeId ? 
        (incoming[0]?.sourceId || state.nodes.find(n => n.id !== nodeId)?.id || null) : 
        state.lastAddedNodeId,
      smartConnections: newSmartConnections
    };
  }),

  // 更新节点位置
  updateNodePosition: (nodeId, position) => set((state) => {
    const newNodes = state.nodes.map(node => 
      node.id === nodeId ? { ...node, position } : node
    );
    
    // 重新计算受影响的连接
    const affectedConnections = state.connections.filter(
      c => c.sourceId === nodeId || c.targetId === nodeId
    );
    
    const newSmartConnections = { ...state.smartConnections };
    affectedConnections.forEach(conn => {
      newSmartConnections[conn.id] = {
        curvature: calculateConnectionCurvature(conn, newNodes),
        avoidCollisions: checkConnectionCollisions(conn, state.connections, newNodes),
        lastUpdated: Date.now()
      };
    });

    return {
      nodes: newNodes,
      smartConnections: newSmartConnections
    };
  }),

  updateNodeParams: (nodeId, params) => set((state) => ({
    nodes: state.nodes.map((node) =>
      node.id === nodeId ? { ...node, parameters: params } : node
    )
  })),

  setNodeStatus: (nodeId, status) => set((state) => ({
    nodes: state.nodes.map((node) =>
      node.id === nodeId ? { ...node, status } : node
    )
  })),

  addConnection: (connection) => set((state) => ({
    connections: [...state.connections, connection],
    smartConnections: {
      ...state.smartConnections,
      [connection.id]: {
        curvature: 0.5,
        avoidCollisions: false,
        lastUpdated: Date.now()
      }
    }
  })),

  removeConnection: (connectionId) => set((state) => {
    const newSmartConnections = { ...state.smartConnections };
    delete newSmartConnections[connectionId];
    
    return {
      connections: state.connections.filter(c => c.id !== connectionId),
      smartConnections: newSmartConnections
    };
  }),

  setSelectedNode: (nodeId) => set({ selectedNodeId: nodeId }),

  updateConnectionPath: (connId) => set((state) => {
    const connection = state.connections.find(c => c.id === connId);
    if (!connection) return state;
    
    return {
      smartConnections: {
        ...state.smartConnections,
        [connId]: {
          curvature: calculateConnectionCurvature(connection, state.nodes),
          avoidCollisions: checkConnectionCollisions(connection, state.connections, state.nodes),
          lastUpdated: Date.now()
        }
      }
    };
  }),

  recalculateAllPaths: () => set((state) => {
    const newSmartConnections: Record<string, SmartConnection> = {};
    
    state.connections.forEach(conn => {
      newSmartConnections[conn.id] = {
        curvature: calculateConnectionCurvature(conn, state.nodes),
        avoidCollisions: checkConnectionCollisions(conn, state.connections, state.nodes),
        lastUpdated: Date.now()
      };
    });
    
    return { smartConnections: newSmartConnections };
  }),

  clearRuntimeData: () => set((state) => ({
    nodes: state.nodes.map(node => ({
      ...node,
      outputs: undefined,
      status: 'idle'
    }))
  })),
}));

// 辅助函数
function calculateConnectionCurvature(
  connection: FlowConnection, 
  nodes: FlowNode[]
): number {
  const source = nodes.find(n => n.id === connection.sourceId);
  const target = nodes.find(n => n.id === connection.targetId);
  if (!source || !target) return 0.5;

  const dx = target.position.x - source.position.x;
  const dy = target.position.y - source.position.y;
  const distance = Math.sqrt(dx * dx + dy * dy);
  
  // 根据角度和距离计算曲率
  return Math.min(0.9, Math.max(0.1, 
    0.5 + (Math.atan2(dy, dx) / Math.PI) * 0.3
  ));
}

function checkConnectionCollisions(
  targetConn: FlowConnection,
  allConnections: FlowConnection[],
  nodes: FlowNode[]
): boolean {
  // 简化的碰撞检测
  return allConnections.some(conn => {
    if (conn.id === targetConn.id) return false;    
    return false; // 待实现实际碰撞检测
  });
}